package greedy.划分字母区间;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<Integer> partitionLabels(String s) {
        /**
         * 先保存每个字母的最大位置，然后再遍历数组时查找当前元素的最大位置
         * 扫描索引可达到最大位置时，可截取
         */
        List<Integer> ans = new ArrayList<>();
        int [] dict = new int[26];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            dict[c - 'a'] = i;
        }
        for (int i = 0; i < s.length(); ) {
            char c = s.charAt(i);
            int count = 1 ;
            int maxIndex = dict[c - 'a'];
            while (i + count <= maxIndex ){
                char c1 = s.charAt(i + count);
                maxIndex = Math.max(maxIndex , dict[c1 - 'a']);
                count++;
            }
            i = i + count;
            ans.add(count);
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution().partitionLabels("ababcbacadefegdehijhklij"));
    }
}
